package cn.ztw.controller;


import cn.ztw.domain.User;
import cn.ztw.downgrade.DowngradeUtil;
import cn.ztw.downgrade.FuseDowngradeUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @BelongsProject: springcloudnetflix-parent
 * @BelongsPackage: cn.itsource.controller
 * @Author: Director
 * @CreateTime: 2022-07-30  14:39
 * @Description: 用户服务接口
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user")
@RefreshScope // 动态刷新配置注解
public class UserController {

    @Value("${server.port}")
    private String port;

    @Value("${dynamicRefreshTest}")
    private String dynamicRefreshTest;

    /*
     * @Description: 提供一个根据Id返回User对象的接口，给order服务调用
     * @Author: Director
     * @Date: 2022/7/30 14:42
     * @param id:
     * @return: cn.itsource.domain.User
     **/
    @GetMapping("/getById/{id}")
    @SentinelResource(value = "user-server-getById", blockHandler = "degradationMethod" ,
            blockHandlerClass = DowngradeUtil.class, fallback = "fuseDegradation", fallbackClass = FuseDowngradeUtil.class)
    public User getById(@PathVariable("id") Long id){
        try {
            // 用于让服务慢响应
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new User(id, "源码时代", "我在源码时代学习Java!，端口号：" + port + ", dynamicRefreshTest：" + dynamicRefreshTest);
    }

    /*
     * @Description: 熔断降级方法
     * @Author: Director
     * @Date: 2022/7/31 1:50
     * @param id:
     * @param e: 降级异常
     * @return: cn.itsource.domain.User
     **/
//    public User fuseDegradation(@PathVariable("id") Long id, Throwable  e){
//        e.printStackTrace();
//        return new User(-1L, "熔断服务降级触发！", "服务不可用，请稍后重试！");
//    }

    /*
     * @Description: 服务降级方法
     * @Author: Director
     * @Date: 2022/7/30 23:26
     * @param id:
     * @param e: 服务降级方法必须接收的异常参数
     * @return: cn.itsource.domain.User
     **/
//    public User degradationMethod(@PathVariable("id") Long id, BlockException e){
//        e.printStackTrace();
//        return new User(-1L, "服务降级触发！", "当前服务流量过大，请稍后重试！");
//    }

}